package common;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONObject;

public class PostJson {

	private static String ENCRYPT_URL = "http://106.15.43.138:8888/en";
	private static String DESCRYPT_URL = "http://106.15.43.138:8888/de";

	public static String post(String json, String url) {
		String line = null;
		try {
			URL url1 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 设置不用缓存
			conn.setUseCaches(false);
			// 设置传递方式
			conn.setRequestMethod("POST");
			// 设置维持长连接
			conn.setRequestProperty("Connection", "Keep-Alive");
			// 设置文件字符集:
			conn.setRequestProperty("Charset", "UTF-8");
			// 转换为字节数组
			byte[] data = (json.getBytes());
			// 设置文件长度
			conn.setRequestProperty("Content-Length", String.valueOf(data.length));
			// 设置文件类型:
			conn.setRequestProperty("Content-Type", "application/json");
			// 开始连接请求
			conn.connect();
			OutputStream out = conn.getOutputStream();
			// 写入请求的字符串
			out.write(json.getBytes());
			out.flush();
			out.close();
			// 请求返回的状态
			if (conn.getResponseCode() == 200) {
				// 请求返回的数据
				BufferedReader in = null;
				in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				line = in.readLine();
			}
		} catch (Exception e) {
		}
		return line;
	}

	public static String postJson(JSONObject json, String url) {
		String enJson = post(json.toString(), ENCRYPT_URL);
		String aJson = post(enJson, url);
		String deJson = post(aJson, DESCRYPT_URL);
		return deJson;
	}

}
